<?php

namespace addons\tools\model;

use think\Model;

class Tools extends Model
{
    protected $name = 'tools';

    protected $append = [
        'font_list',
        'font_list1'
    ];

    private $flags = [
        1 => 'hot',
        2 => 'surname',
        3 => 'zodiac',
    ];

    public function getImagesAttr($value)
    {
        $images = explode(',', $value);
        if (!empty($images)) {
            return array_map(function ($item) {
                return cdnurl($item, false, true);
            }, $images);
        }
        return null;
    }

    public function getDefaultFontAttr($value)
    {
        if ($value) return Font::where('id', $value)->value('third_id');
        return null;
    }

    public function getDefaultFont1Attr($value)
    {
        if ($value) return Font::where('id', $value)->value('third_id');
        return null;
    }

    public function getDefaultTemplateAttr($value)
    {
        if ($value) return Template::where('id', $value)->value('third_id');
        return null;
    }

    public function getFontListAttr($value, $data)
    {
        if (!empty($data['font_ids'])) {
            return \addons\tools\model\Font::whereIn('id', explode(',', $data['font_ids']))->field('third_id,image,name')->select();
        }
        return [];
    }

    public function getFontList1Attr($value, $data)
    {
        if (!empty($data['font1_ids'])) {
            return \addons\tools\model\Font::whereIn('id', explode(',', $data['font1_ids']))->field('third_id,image,name')->select();
        }
        return [];
    }

    public function getLists($params)
    {
        $model = $this->field('id,name,images');
        if (!empty($params['flag'])) {
            $model = $model->where('find_in_set(:flag,flag)', ['flag' => $this->flags[$params['flag']]]);
        }
        if (!empty($params['category_id'])) {
            $model = $model->where('category_id', $params['category_id']);
        }
        return $model->where('status', 'normal')
            ->order('weigh', 'DESC')
            ->order('create_time', 'desc')->paginate($params['page_size'] ?: 10);
    }

    public function getDetailById($id)
    {
        return $this->field('id,name,category_id,desc,images,page,source,code,file,font_ids,font1_ids,default_font,default_font1,default_color,default_color1,default_surname,default_declaration,default_zodiac,default_template')->with(['template' => function ($query) {
            $query->field('id,tool_id,name,third_id');
        }])->with(['category' => function ($query) {
            $query->field('id,name,code');
        }])->where('status', 'normal')->find($id);
    }

    public function template()
    {
        return $this->hasMany(Template::class, 'tool_id', 'id');
    }

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }

}